package auth_controller

import (
	"fmt"
	"gin-project/database"
	"gin-project/entity"
	"net/http"

	"github.com/gin-gonic/gin"
)

func Login(c *gin.Context) {
	var user entity.User
	if err := c.ShouldBindJSON(&user); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "参数错误",
			"success": false,
		})
		return
	}
	username := user.Username
	password := user.Password
	if username == "" || password == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "参数错误",
			"success": false,
		})
		return
	}
	sqlStr := fmt.Sprintf("select * from tb_user where username = '%s' and password = '%s'", username, password)
	var userList []entity.User
	result := database.DB.Raw(sqlStr).Scan(&userList)
	if result.Error != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "用户名或密码错误",
			"success": false,
		})
		return
	}
	if len(userList) == 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "用户名或密码错误",
			"success": false,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "登录成功",
		"success": true,
		"data": gin.H{
			"token": "1234567890",
		},
	})
}
